﻿using System;
using System.Data;
using System.IO;
using System.Drawing;

namespace Home.Haushalt.Lib.Element
{
    /// <summary>
    /// 
    /// </summary>
    [ElementExtension("Element")]
    public class Page : ElementBase
    {
        #region CONSTANTS
        public new static readonly Type ElementType = typeof(Page);

        /// <summary></summary>
        public class Fields
        {
            public const string Id = ELEMENTPROPERTY_ID;
            public const string Index = "n";
            public const string DocumentId = "d";
            public const string TypeId = "t";
            public const string SourceFileName = "f";

            public const string UnboundFilePath = "filepath";
            public const string UnboundFileExists = "fileexists";
        }
        #endregion CONSTANTS

        /// <summary></summary>
        private DataTable _elementTable;

        /// <summary></summary>
        public override DataTable ElementTable
        {
            get
            {
                if (_elementTable == null) 
                    _elementTable = DAO.Tables[this.GetType()];
 
                return _elementTable;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tbl"></param>
        public void SetElementTable(DataTable tbl)
        {
            _elementTable = tbl;
        }

        /// <summary></summary>
        private DataRow _docuDataRow;

        /// <summary></summary>
        public string FilePath
        {
            get
            {
                string filename = "";

                if (_docuDataRow != null)
                {
                    string repoFileName = CreateFileStoreName(_docuDataRow);
                    filename = Path.Combine(DAO.HFile.FileStoreFullPath, repoFileName);
                }

                return filename;
            }
        }

        /// <summary></summary>
        public string DecryptFilePath
        {
            get
            {
                return this.Crypted ? DAO.HFile.GetDecryptedFileTry(this.FilePath) : this.FilePath;

                //string tempFileName = this.FilePath;

                //if (this.Crypted)
                //{
                //    tempFileName = Path.Combine(DAO.TempFullPath, Path.GetFileName(this.FilePath));

                //    if (!File.Exists(tempFileName))
                //    {
                //        //In Temp kopieren
                //        try
                //        {
                //            File.Copy(this.FilePath, tempFileName, true);
                //        }
                //        catch (Exception ex)
                //        {
                //            Journal.Add(this, "Datei [" + this.FilePath + "] in Temp [" + tempFileName + "] kopieren", ex);
                //            return this.FilePath;
                //        }

                //        //Decrypten
                //        try
                //        {
                //            DAO.Credential.CurrentCry.FileDecrypt(tempFileName);
                //        }
                //        catch (Exception ex)
                //        {
                //            Journal.Add(this, "Datei [" + tempFileName + "] decrypten", ex);
                //            return this.FilePath;
                //        }
                //    }
                //}

                //return tempFileName;
            }
        }

        /// <summary></summary>
        public bool Crypted { get { return _docuDataRow[Document.Fields.Crypted].ToBool(false); } }

        /// <summary>
        /// 
        /// </summary>
        public Page() : base() { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentDataRow"></param>
        public Page(DataRow parentDataRow) : base(parentDataRow) { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="parentDataRow"></param>
        internal override void Init(DataRow parentDataRow)
        {
            base.Init(parentDataRow);

            if (CheckColumnsInRow(Fields.DocumentId))
            {
                DataRow[] docuRows = DAO.GetSubRows(Document.ElementType, Document.Fields.Id, Row[Fields.DocumentId]);
                if (docuRows.Length > 0)
                {
                    _docuDataRow = docuRows[0];
                }
            }
        }

        /// <summary>
        /// Definition des Datei-Namen laut aktueller Properties
        /// </summary>
        /// <param name="docuRow"></param>
        /// <param name="pageRow"></param>
        /// <returns></returns>
        public string CreateFileStoreName(DataRow docuDataRow)
        {
            string result = "";
            DateTime datum = docuDataRow[Document.Fields.Date].ToDateTime();

            //Datum Zeichen: 0-8
            result = datum.Year.ToString() + datum.Month.ToString("00") + datum.Day.ToString("00");

            //Weg (Brief, Email, Fax) Zeichen: 9
            object wayIdent = DAO.GetPropertyAtId(Way.ElementType, docuDataRow[Document.Fields.WayId], Way.Fields.Ident);
            result += wayIdent != null ? wayIdent.ToString() : "ERROR";

            //Richtung (Eingang, Ausgang) Zeichen: 10
            object directionIdent = DAO.GetPropertyAtId(Direction.ElementType, docuDataRow[Document.Fields.DirectionId], Direction.Fields.Ident);
            result += directionIdent != null ? directionIdent.ToString() : "ERROR";

            //DocuID Zeichen: 11-14
            result += docuDataRow[Document.Fields.Id].ToInt().ToString("0000");

            //Opponent (BIG, Finanzamt...)
            object opponentIdent = DAO.GetPropertyAtId(Opponent.ElementType, docuDataRow[Document.Fields.OpponentId], Opponent.Fields.Ident);
            result += opponentIdent != null ? opponentIdent.ToString() : "ERROR"; ;

            //Kategorie
            object docuTypeName = DAO.GetPropertyAtId(Docutype.ElementType, docuDataRow[Document.Fields.DocuTypeId], Docutype.Fields.Name);
            result += docuTypeName != null ? docuTypeName.ToString() : "ERROR"; ;

            //Pageindex (01,02...10,11...)
            result += Row[Fields.Index].ToInt().ToString("00");

            //Extention (.doc, .jpg...)
            object pageExtansion = DAO.GetPropertyAtId(FileType.ElementType, Row[Fields.TypeId], FileType.Fields.Ext);
            result += pageExtansion != null ? pageExtansion.ToString() : "ERROR"; ;

            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override int Delete()
        {
            if (ID > -1)
            {
                //Datei löschen
                DAO.HFile.Delete(this.FilePath);

                return base.Delete();
            }
            else
            {
                ElementTable.Rows.Remove(Row);
                return -1;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="encrypt">true = encrypt; false = decrypt</param>
        /// <returns></returns>
        internal bool Crypt(bool encrypt)
        {
            try
            {
                if (encrypt)
                {
                    DAO.Credential.CurrentCry.FileEncrypt(this.FilePath);
                }
                else
                {
                    DAO.Credential.CurrentCry.FileDecrypt(this.FilePath);
                }
                return true;
            }
            catch (Exception ex)
            {
                Journal.Add(this, "Fehler beim Datei-Uumschlüsseln  [" + this.FilePath + "]", ex);
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override Color GetRowForeColor()
        {
            Color foreColor = base.GetRowForeColor();

            if (Row[Page.Fields.Id].ToInt() == -1)
                foreColor = DAO.Settings.Selected.RowStateNewPage;

            return foreColor;
        }

    }
}
